package com.jyxd.web.hiscz.webservice;


import cn.hutool.json.XML;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


public class WebService {

    private static Logger logger = LoggerFactory.getLogger(WebService.class);

    public static Map<String, Object> requestWebService(String localPart, String xml) {
        try {
            String result = doRequest(localPart, xml);
            if (StringUtils.isEmpty(result))
                return null;
            return getReturn(result);
        } catch (Exception e) {
            logger.error("单点登录接口接收错误 ---" + e.getMessage());
            return null;
        }
    }


    public static void main(String[] args) {
        String s = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "<soap:Header/><soap:Body><LoginInfoRegisterResponse xmlns:ns2=\"http://tempuri.org/\" xmlns=\"http://tempuri.org/\">" +
                "<LoginInfoRegisterResult>" +
                "&lt;?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\"?&gt;&lt;output&gt;&lt;retcode&gt;AA&lt;/retcode&gt;&lt;msg&gt;娉ㄥ唽鎴愬姛&lt;/msg&gt;&lt;/output&gt;" +
                "</LoginInfoRegisterResult></LoginInfoRegisterResponse></soap:Body></soap:Envelope>";
        // Map aReturn = getReturn(s);
        //System.out.println(aReturn);
    }

    private static Map getReturn(String xml) {
        if (StringUtils.isEmpty(xml))
            return null;
        xml = xml.replaceAll("&lt;", "<").replaceAll("&gt;", ">");
        int start = xml.indexOf("<output>");
        int end = xml.indexOf("</output>");
        xml = xml.substring(start, end);
        xml = xml.replace("<output>", "");
        return returnToJson(xml);
    }


    private static Map returnToJson(String xml) {
        JSONObject xmlJSONObj = JSONObject.fromObject(XML.toJSONObject(xml));
        return xmlToJsonMap(xmlJSONObj);
    }

    /**
     * xml转JsonMap
     *
     * @param xmlJSONObj
     * @return
     */
    public static Map<String, Object> xmlToJsonMap(Object xmlJSONObj) {
        return com.alibaba.fastjson.JSONObject.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(xmlJSONObj), HashMap.class);
    }

    /**
     * webservice请求
     *
     * @param method   调用方法
     * @param paramXml 拼接的xml
     * @return
     */
    public static String doRequest(String method, String paramXml) {
        try {
            String url = "http://172.21.101.63:8080/jcpt/ws/sso.wsdl";
            // 1 创建URL：
            URL req_url = new URL(url);
            //2：打开一个通向服务地址的连接
            HttpURLConnection con = (HttpURLConnection) req_url.openConnection();
            con.setConnectTimeout(30000);// 设置连接主机超时时间（毫秒）
            con.setReadTimeout(30000);// 设置主机读取数据超时
            // 3，设置请求方式和请求头：
            con.setDoInput(true); // 是否有入参
            con.setDoOutput(true); // 是否有出参
            con.setRequestMethod("POST"); // 设置请求方式
            con.setRequestProperty("connection", "Keep-Alive");
            con.setRequestProperty("user-agent", "Apache-HttpClient/4.1.1");
            con.setRequestProperty("content-type", "text/xml;charset=utf-8");
            // 5，通过流的方式将请求体发送出去：
            OutputStream out = con.getOutputStream();
            out.write(getParamXml(method, paramXml).getBytes("utf-8"));
            out.flush();
            out.close();
            // 6，服务端返回正常：
            int code = con.getResponseCode();
            logger.info("请求返回 HTTP CODE 为 --" + code);
            String result = null;
            if (code == 200) {// 服务端返回正常
                InputStream is = con.getInputStream();
                byte[] b = new byte[1024];
                StringBuffer sb = new StringBuffer();
                int len = 0;
                while ((len = is.read(b)) != -1) {
                    String str = new String(b, 0, len, "UTF-8");
                    sb.append(str);
                }
                result = sb.toString();
                is.close();
                con.disconnect();
            }
            return result;
        } catch (Exception e) {
            logger.info("调用单点登录接口错误：" + e.getMessage());
            return null;
        }
    }

    /**
     * 拼接请求参数
     *
     * @param method
     * @param paramXml
     * @return
     */
    private static String getParamXml(String method, String paramXml) {
        StringBuffer strBuffer = new StringBuffer();
        String xml="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <tem:"+method+">\n" +
                "         <tem:inputdata>\n" +
                "        <![CDATA[\n" +paramXml+

                "         ]]>\n" +
                "         </tem:inputdata>\n" +
                "      </tem:"+method+">\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        logger.info("请求单点登录参数值为：" + xml);
        return xml;
    }
}
